<?php
include("../inc/head.php");
include '../wondershare/configs/site_config.php';

if ( $_GET['type'] == 'update_state' && !empty($_GET['Tid']) ) {
	
	
	$Tid = (int) $_GET['Tid'];
	$sql = "UPDATE Table_{$Tid}
			SET MendTime = {$_SERVER['REQUEST_TIME']}";
	$db->query($sql);
	alert("修改生成状态为已修改成功！", "location", $_SERVER['HTTP_REFERER']);
	exit;
}


//note 以ajax形式发布时不要输出头部文件
if( $_REQUEST["ajax_pub"] ) {
	ob_start();
}

//设置可以全部生成以及不计cdn文件的表数组
$nocnd_tables_array = array(75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 88, 91, 92, 93, 94, 95, 99, 
							148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 162, 163, 166,
							215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228
							);
$sort = $_GET['sort'];
$sortby = $_GET['sortby'];

{DOC_CONF}

if ( $Template->PID != 0 ){
	
	$Templatep = new Template();

	$Templatep->getObjById($Template->PID, 'TID', 'Template');
	$psql = "SELECT D_ID, url 
			FROM `$Templatep->DTName` 
			LIMIT 1";
	$prow_ = $db->query($psql);
	$prow = $db->fetch_array($prow_);
}

$site_id = (int) $_GET['site_id'];//站点ID

if ( empty($site_id) ) {
	
	$sql = "SELECT web_type 
			FROM Template 
			WHERE TID = {$Template->TID} 
			LIMIT 1";
	$web_type = (int) $db->getOne($sql);
	$site_id = (int) $GLOBALS['size_to_webtype'][$web_type];

}

/********end*************/
$count = count($idStr);
for ( $i = 0; $i < $count; $i++) {
	
	$sqlStr .= $fieldStr[$i].", ";
	$titleStr .= "<td>{$nameStr[$i]}</td>";
}

/*文章搜索功能*/
$sql_where = $act_url = '';
for ( $i = 0; $i < 5; $i++ ) {
	
	$search[$i]['Field'] = preg_replace("[^A-Za-z0-9_]", "", $_REQUEST['Field_'.$i]);
	$search[$i]['Field_Name'] = trim($_REQUEST['Field_Name_'.$i]);
	$search[$i]['Value'] = $_REQUEST['F_'.$i.'_V'];
	$search[$i]['Option'] = $_REQUEST['Option_'.$i];
	$search[$i]['Next'] = $_REQUEST['Next_'.$i];
	
	if ($search[$i]['Option'] != '=' && $search[$i]['Option'] !='!=' && 
		$search[$i]['Option'] !='>' && $search[$i]['Option'] !='<' && 
		$search[$i]['Option'] !='>=' && $search[$i]['Option'] !='<=' && 
		$search[$i]['Option'] !='like' && $search[$i]['Option'] !='not like') {
			
		$search[$i]['Option'] = '=';
	}
	
	if ($search[$i]['Field'] && $search[$i]['Value']) {
		
		$search[$i]['Value'] = trim($search[$i]['Value']);
		
		if ($search[$i]['Field']=='Creator') {
			$search[$i]['Value'] = getAdminIdByName($search[$i]['Value']);
			$search[$i]['Field'] = "CreatorID";
		}
		
		if ($search[$i]['Field']=='Mender') {
			$search[$i]['Value'] = getAdminIdByName($search[$i]['Value']);
			$search[$i]['Field'] = "MenderID";
		}
		
		if ($search[$i]['Field']=='CreateTime') {
			
			$search[$i]['Field'] = 'left(from_unixtime(CreateTime),'.strlen($search[$i]['Value']).')';
		}
		
		if ($search[$i]['Field']=='MendTime') {
			
			$search[$i]['Field'] = 'left(from_unixtime(MendTime),'.strlen($search[$i]['Value']).')';
		}
		
		if (ereg("like",$search[$i]['Option'])) {
			$sql_where .= " AND ".$search[$i]['Field']. ' ' .$search[$i]['Option']." '%" . $search[$i]['Value'] . "%'";
		} elseif ($search[$i]['Option']) {
			$sql_where .= " AND ".$search[$i]['Field'] . ' ' .$search[$i]['Option']." '" . $search[$i]['Value'] . "'";
		}
		
		$sqlStr .= ' '.$search[$i]['Field'].', ';
		
		//note 当搜索的是'url','MenderID','MendTime'时，不在表格列表中重复显示这些列
		if ( !in_array( $search[$i]['Field'], array('url','MenderID','MendTime')) ) {
			$titleStr .= ' <td>'.$search[$i]['Field_Name'].'</td> ';
		}
		
		$fieldStr[] = $search[$i]['Field'];
		$idStr[] = $search[$i]['Field'];
	}
	

	//note 筛选是否生成html
	$create_html = $_REQUEST['create_html'];
	if ( $create_html[0] != '' ) {
		$sql_where .= $create_html[0] == 1 ? ' AND CreateTime > 0' : ' AND CreateTime = 0';	
		$c_html = $create_html[0];
	}
	
	if ( !$search[$i]['Next'] ) {
		$i = 5;
	}

}

//修改未生成的文件的创建时间为0
updateNoFileExistsTime($Template->DTName);
/*******/
$page = 1;
if (!empty($_REQUEST['page'])) {
	$page = (int) $_REQUEST['page'];
}

$start = 0;
$pagesize = 20;
/* 修改分页功能 朱志雄 2008-6-23 */
$total = 0; //总数
$sql_p = "  SELECT COUNT(*) 
			FROM {$Template->DTName} 
			WHERE 1=1 {$sql_where}";
if ( $res_p = $db->query($sql_p) ) {
	if ($row_p = $db->fetch_array($res_p)) {
		$total = $row_p[0];
	}
}

$page_num = ceil($total/$pagesize);
if ($page_num < 1) {
	$page_num = 1;
}
if ($page > $page_num) {
	$page = $page_num;
}

$start = ($page - 1) * $pagesize;

/***zhu End***/

if (!$sortby) {
	$order = "D_ID DESC"; 
} else {
	$order = $sortby . ' ' .$sort ;
}

/**yuantuan修改2011-06-13*/
$str_from_id='';

switch ($Template->DTName) {
	
   case 'Table_13':
     $str_from_id = " Field_19965 as fromid,";
     break;
   case 'Table_15':
     $str_from_id = " Field_19930 as fromid,";
     break;
   case 'Table_19':
     $str_from_id = " Field_19983 as fromid,";
     break;

}
//投放单页表的相关表
$product_tables = array('Table_26' => array('table' => 'Table_26', 'sing_table' => 'Table_45', 'Field_id' => 'Field_20044'),
						'Table_23' => array('table' => 'Table_23', 'sing_table' => 'Table_45', 'Field_id' => 'Field_20071'),
						'Table_34' => array('table' => 'Table_34', 'sing_table' => 'Table_45', 'Field_id' => 'Field_20208'),
						'Table_33' => array('table' => 'Table_33', 'sing_table' => 'Table_45', 'Field_id' => 'Field_20182'),
						'Table_39' => array('table' => 'Table_39', 'sing_table' => 'Table_74', 'Field_id' => 'Field_20326')
					);
				
//设置投放的单页管理模板表
$product_single_table = array(  'Table_45' => array('tem_id' => 'Field_20350'),
								'Table_74' => array('tem_id' => 'Field_20734')
						);

$tables_name = $Template->DTName ;
$is_open = $where_open = ''; 
$open_fage = $is_single = 0;

if ( !empty($product_tables[$tables_name]) ) {
	
   $tem_id = $product_single_table[$product_tables[$tables_name]['sing_table']]['tem_id'];//单页管理表id
   $tem_table = $product_tables[$tables_name]['sing_table'];//单页管理表名称
   $ws_id = $product_tables[$tables_name]['Field_id'];//单页表的相关表wsid
   
   if ($page == 1) {
   	 //设置为0以防单页删除
   	  $sql = "UPDATE $tables_name 
   	  		  SET is_open = 0 ";
	  $db->query($sql);
	  
      $sql = "SELECT $tem_id, url 
      		  FROM $tem_table  WHERE is_open = 0 ";
	  $result = $db->query($sql);
	  
	  while ($rs = $db->fetch_array($result)) {
	  	
		$sql = "UPDATE $tables_name 
				SET is_open = 1 
				WHERE  $ws_id = '{$rs[$tem_id]}' AND url = '{$rs['url']}' ";
		$db->query($sql);
	 }
	 
	 $sql = "SELECT $tem_id, url 
	 		FROM $tem_table  
	 		WHERE is_open = 1 ";
	 $result = $db->query($sql);
	 
	 while ($rs = $db->fetch_array($result)) {
	 	
		$sql = "UPDATE $tables_name 
				SET is_open = 0 
				WHERE  $ws_id = '{$rs[$tem_id]}' AND url = '{$rs['url']}' ";
		$db->query($sql);
	 }
   }
	$is_open = ' ,is_open ';
  	$open_fage = 1;
  	$where_open =  'AND is_open = 0 ';
  	
} elseif (!empty($product_single_table[$tables_name]) ) {
   $is_open = ' ,is_open ';
   $open_fage = 1;
   $is_single = 1;
   $where_open =  'AND is_open = 0 ';
}

$sql = "SELECT {$sqlStr} {$str_from_id} D_ID, CreateTime, CreatorID, MendTime, MenderID, url $is_open 
		FROM {$Template->DTName} 
		WHERE 1 = 1 {$sql_where} 
		ORDER BY {$order} 
		LIMIT {$start}, {$pagesize}";
//note 当$_REQUEST["ajax_pub"]有值时为通过ajax形式发布
$is_ajax_pub = $_REQUEST["ajax_pub"];

$mEditFile = trim($_REQUEST["mEditFile"]);
$mDeleteFile = trim($_REQUEST["mDeleteFile"]);
$mCdnEditFile = trim($_REQUEST["mCdnEditFile"]);
$mCdnDeleteFile = trim($_REQUEST["mCdnDeleteFile"]);

if($_REQUEST['doPost'] == "true" || $is_ajax_pub ){
	
	if( $is_ajax_pub ){
		
		$sql_get_did = "SELECT D_ID 
						FROM {$DTName} 
						WHERE Field_{$_REQUEST['field_id']} = {$_REQUEST['key_id']}   ";
		$did = $db->getOne( $sql_get_did );
		
		$IDS = array( 0 => $did );
	} else {
		$IDS = $_REQUEST["ID"];
	}
		
	if ( !is_array($IDS) ) {
		alert("请选择要操作的文档");
	}
	
	//单页删除
	if ($_POST['action'] == "del") {
		
		$file_row = checkIsTask($site_id, 0);
		foreach ($IDS as $ID) {
			
			$Doc = new Object();
			$Doc->getObjById($ID,"D_ID",$DTName);
			delDoc($Doc, $file_row);
			
			if ($DTName=='Table_15' || $DTName=='Table_19') {
				delPageList($ID,"D_ID",$DTName);
			}
			new ActionLog(array("LogType"=>"doc_{$TID}_del","Action"=>"$ID\t{$currAdmin->AID}"));
		}
		
		$sqlstr = implode(",",$IDS);
		/**yuantuan添加2011-06-13 删除页面模版同时更新信息库的发布状态值*/
		$select_name = '';
		switch ($DTName) {
			
		    case 'Table_13':
			  $select_name = 'Field_19965';
			  break;
		    case 'Table_15':
			  $select_name = 'Field_19930';
			  break;
		    case 'Table_19':
			  $select_name = 'Field_19983';
			  break;
		}
		
		if ($select_name && $DTName && $sqlstr) {
			
			$sql_art = "SELECT $select_name 
						FROM $DTName 
						WHERE D_ID 
						IN ($sqlstr)";
			$result = $db->query($sql_art);
			
			while ($rows_art=$db->fetch_array($result)) {
				
				 $array_id[] = $rows_art[$select_name];
			}
			
			$sqlstr_art = implode(",", $array_id);
			
			switch ($DTName) {
				
				case 'Table_13':
				  $id = 'ar_id';
				  $t_name='topic_article';
				  break;
				  
				case 'Table_15':
				  $id = 'cat_id';
				  $t_name='category';
				  break;
				  
				case 'Table_19':
				  $id = 'tag_id';
				  $t_name='tag';
				  break;
			}
			
			if ($t_name && $id) {
				$sql =  "UPDATE $t_name 
						SET `pub_time`=0, `pub_status`=0, `modify_status` = 0, `template_url`=0 
						WHERE $id IN ($sqlstr_art)";
				$db->query($sql);
			}
		
		}
		//$sqlstr = implode(",",$IDS);
		$sql = "DELETE 
				FROM $DTName 
				WHERE D_ID IN ($sqlstr)";
		if ($db->query($sql)) {
			alert("删除成功","location",$_SERVER["SCRIPT_NAME"]);
		}
		
	} elseif ($_REQUEST['action'] == "pub") { //单页发布
		
			$file_row = checkIsTask($site_id, 0);
			
		   $str_id = '';
		   foreach($IDS as $ID) {
				
		   		$str_id .= empty($str_id) ? $ID : ','.$ID;
			}
			
			if ( !empty($str_id)) {
				

				//判断是否是木有用于cdn表
				if (!array_search(str_replace('Table_', '', $DTName), $nocnd_tables_array)) {
					
					$sql = "SELECT D_ID, url
							FROM {$DTName} 
							WHERE  FIND_IN_SET(D_ID, '{$str_id}')  AND CreateTime = 0  $where_open 
							UNION ALL 
							SELECT D_ID, url
							FROM {$DTName} 
							WHERE FIND_IN_SET(D_ID, '{$str_id}')   AND MendTime > CreateTime $where_open ";
			
				} else {
					
					$sql = "SELECT D_ID, url
							FROM {$DTName} 
							WHERE  FIND_IN_SET(D_ID, '{$str_id}')    $where_open ";
				}
			
				
				$rows = $db->getAll($sql);
				
				foreach ($rows AS $key => $value) {
					
					create_pub($value['D_ID'], $value['url'], $DTName, $file_row);
					//note 更新文档生成时间和生成人
					$sql = "UPDATE {$Template->DTName} SET CreateTime = ".$_SERVER['REQUEST_TIME']."
							WHERE D_ID = " .$value['D_ID'];
			
					$db->query($sql);
				}
			}
		
		if ( $is_ajax_pub ) {
			ob_end_clean();//清空引入的头部文件
			echo 1;
			exit;
		} else {
			if ( $_GET['is_disqus_pub'] ) {
				
				$url = 'http://cms.wondershare.com.br.wx/disqus/syn_comment.php?m=create_ok&sid='.$_GET['sid'].'&d_id='.implode(',',$IDS);
				echo '<script type="text/javascript">window.location.href="'.$url.'";</script>';
				exit;
			}
			alert("生成静态页成功","location",$_REQUEST['gotourl']);
		}
		
		
	} elseif ($_REQUEST['action'] == "pubtmp") {
		
		foreach ($IDS as $ID) {
			
			$Doc = new Object();
			/******2010.05.05预览功能修改***************/
			//判断是否为根层，根层则发布本身。
			if ($Template->PID==0) {
				$Doc->getObjById($ID,"D_ID",$DTName);
				createDoc($Doc,1);
			} else {
				
				$Doc = new Object();
				$Doc->getObjById($ID,"D_ID",$DTName);
				createDoc($Doc,0);
				echo '<script type="text/javascript" src="docList_'.$Template->PID.'.php?doPost=true&ID[]='.$prow['D_ID'].'&action=pubtmp"></script>';
			}
			/************end**************/
		}
		alert("生成页面预览成功","location",$_SERVER["SCRIPT_NAME"]);
	}
	exit;
}
//以下判断为全部生成
if ($_REQUEST['action'] == "all") {
	
	$file_row = checkIsTask($site_id, 0);
    if (!empty($where_open)) {
	    $where_open = " AND  is_open = 0 ";
	}




	//判断是否是木有用于cdn表

	if (!array_search(str_replace('Table_', '', trim($DTName)), $nocnd_tables_array)) {
		$sql = "SELECT D_ID ,url
				FROM {$DTName} 
				WHERE CreateTime = 0 {$where_open} 		
				UNION ALL 		
				SELECT D_ID , url
				FROM {$DTName} 
				WHERE MendTime > CreateTime {$where_open} ";

	} else {
		
		$sql = "SELECT D_ID ,url
				FROM {$DTName} 
				WHERE 1=1 {$where_open} ";
	}
  
    
	$result = $db->query($sql);
    $str_D_ID = '';
	while ($rs = $db->fetch_array($result)) {
		
	     create_pub($rs['D_ID'], $rs['url'], $DTName, $file_row);
		$str_D_ID .= ','.$rs['D_ID'];
	}
	
	$str_D_ID = substr($str_D_ID, 1, strlen($str_D_ID));
	
	$sql = "UPDATE {$DTName}  
			SET CreateTime = '{$_SERVER['REQUEST_TIME']}'  
			WHERE FIND_IN_SET(D_ID, '{$str_D_ID}' ) ";
	$db->query($sql);
	unset($rs);
	
	alert("文章页已全部生成","location",$_REQUEST['gotourl']);
}

if ($_REQUEST['action'] == "single") {
	
    $sql = 'UPDATE '.$tables_name.'  
    		SET is_open = '.$_REQUEST['is_open'].' 
    		WHERE D_ID = '.$_REQUEST['tem_id'];
	$db->query($sql);
	
	$sql =  'SELECT  D_ID, url 
			FROM  '.$tables_name.'  
			WHERE D_ID = '.$_REQUEST['tem_id'];
	$rows = $db->getAll($sql);
	
	if ($_REQUEST['is_open'] == 0 ) {
		
		$Doc = new Object();
		$Doc->getObjById($rows[0]['D_ID'],"D_ID",$DTName);
		createDoc($Doc,0);
	    alert("已经启动成功","location",$_SERVER["SCRIPT_NAME"]);
	    
	} else {
		
	     @unlink(DOC_ROOT."/".$rows[0]['url']);
	     alert("已经禁止成功","location",$_SERVER["SCRIPT_NAME"]);
	     
	}
}

//发布函数
function  create_pub($D_ID, $url, $DTName, $file_row) {
	
	$Doc = new Object();
	$Doc->getObjById($D_ID, "D_ID", $DTName);
	createDoc($Doc, 0);
	
	
	$rows = urlToWebUrl($url);
	if ( !empty($rows['web_name'])) {
		insertFile($file_row['mCdnDeleteFile'], $file_row['mCdnEditFile'], $rows['web_url'], 'edit');
		insertFile($file_row['mDeleteFile'], $file_row['mEditFile'], DOC_ROOT.$url, 'edit');
	}

		
}

//删除函数
function delDoc($Doc, $file_row) {

	if (!preg_match("/^http:\/\//i",$Doc->url)) {
		
		if (is_file(DOC_ROOT."/".$Doc->url)) {
			
			@unlink(DOC_ROOT."/".$Doc->url);
	
			$rows = urlToWebUrl($Doc->url);
			if ( !empty($rows['web_name'])) {
				insertFile($file_row['mCdnDeleteFile'], $file_row['mCdnEditFile'], $rows['web_url'], 'delete');
				insertFile($file_row['mDeleteFile'], $file_row['mEditFile'], DOC_ROOT.$Doc->url, 'delete');
	
			}
			
		}
		
	}
}

function createDoc($Doc) {
	
	$Doc = addslashes_deep($Doc);

	$path = $Doc->url;
	if (!preg_match("/^http:\/\//i",$Doc->url)) {
		
		global $Template,$db;
		//
		{DOC_CREATE}
		
		$Doc->YYYY = date("Y", $Doc->CreateTime);
		$Doc->MM = date("m", $Doc->CreateTime);
		$Doc->DD = date("d", $Doc->CreateTime);
		$Doc->HH = date("H", $Doc->CreateTime);
		$Doc->II = date("i", $Doc->CreateTime);
		$Doc->SS = date("s", $Doc->CreateTime);
		$file = $Template->Style;

		//处理全局变量
		preg_match_all ("/\\\$G\{([^\s\}]+)\}/", $file, $matches);
		$count = count($matches[0]);
		for ($i = 0; $i< $count; $i++)  {
			$Global = new Object();
			$Global->getObjById($matches[1][$i], 'Title', 'Global');
			if ($Global->GID > 0) {
				$file = str_replace($matches[0][$i], $Global->Content, $file);
			}
		}
       
		//处理内容
		preg_match_all ("/\\$\{([^\s\}]+)\}/", $file, $matches);
		$count = count($matches[0]);
		for ($i = 0; $i < $count; $i++)  {
			
			if (isset($Doc->$matches[1][$i]))
				$file = str_replace($matches[0][$i], $Doc->$matches[1][$i], $file);
		}
		$file = stripslashes($file);
		
		//新模板替换开始
		$temPrefixName = $Template->TType;
		if (!empty($temPrefixName)) {//新模板替换处理
			
			foreach ($Doc AS $key => $value) {
				
				$_GET[$key] = $value;
			}
			
			$_GET['tem_style'] = $file;
			$_GET['TID'] = $Template->TID;
			
			//以下把字符串转化成php代码
	        preg_match_all ("/\<\?php(.*?)\?\>/", $file, $matches);
	        $count = count($matches[0]);
			for ($i = 0; $i < $count; $i++)  {
				echo  eval($matches[1][$i]);
			}
			
			//把php代码为空
		 	preg_match_all ("/\<\?php(.*?)\?\>/", $file, $matches);
		 	$count = count($matches[0]);
			for ($i = 0; $i < $count; $i++)  {
				$file = str_replace($matches[0][$i],'',$file);
			}
			
			$_GET['temPrefixName'] = $temPrefixName;
			//数组 转化成GET
			arr_to_gets($arr );
			//加载新的替换类
			include_once(dirname(__FILE__).'/../new_template/public_template.php');//用于新模板替换
			$newTem = new PublicTemplate();
			//处理内容
			preg_match_all ("/\\$\{([^\s\}]+)\}/", $file, $matches);
			$count = count($matches[0]);
			for ($i = 0; $i< $count; $i++)  {
				
				$FType = $GLOBALS['db']->getOne('SELECT FType FROM Field WHERE TID = '.$Template->TID.' AND 
												FName = "'.$matches[1][$i].'"  LIMIT 1 ');
				if ($FType == 'Application::SqlResult' || empty($FType) ) {
					
					$file = str_replace($matches[0][$i], $newTem->callsWebClass($_GET,$matches[1][$i]), $file);
				}
			}
			
		}
		////新模板替换结束
		
		//二次处理
		preg_match_all ("/\\$\{([^\s\}]+)\}/", $file, $matches);
		$count = count($matches[0]);
		for ($i = 0; $i< $count; $i++)  {
			if (isset($Doc->$matches[1][$i]))
				$file = str_replace($matches[0][$i], $Doc->$matches[1][$i], $file);
		}

		//处理URL
		preg_match_all ("/\\$\{([^\s\}]+)\}/", $path, $matches);
		$count = count($matches[0]);
		for ($i = 0; $i < $count; $i++)  {
			if (isset($Doc->$matches[1][$i]))
				$path = str_replace($matches[0][$i], $Doc->$matches[1][$i], $path);
		}
		/******2010.05.05预览功能修改***************/
		//$path_tmp=($yid!=0)?$version_url."/".$path:"/".$path;//判断生成的是否预览
		//加入创建时间信息
		$file = $file."
		<!--{$Doc->TID}_{$Doc->D_ID}_".date("Y-m-d H:i:s")."-->";
		//创建/更新文件
		
		$cache = new Cache(array("Content"=>$file,"FilePathName"=>DOC_ROOT.$path));
		/**********end****************/
		$cache->update();
		return $path;
	}
}
?>

<script type="text/javascript">
function show(tr){
	$("#searchline").val(parseInt($("#searchline").val())+1);
	document.getElementById('TR_'+tr).style.display='';
	return false;
}
function hide(tr,count){
	for(i=tr;i<count;i++){
		document.getElementById('TR_'+i).style.display='none';
	}
	$("#searchline").val(parseInt($("#searchline").val())-1);
	return false;
}

function checkFrom(){
	var r = document.getElementById('gotopage').value;
	if( r ) return false;
	return confirm('该操作不可恢复，确认进行该操作');	
}

//note 按修改时间排序
function _sort( field ){
	$("#sortby").val( field );
	if( $("#sort").val() == 'ASC' ) $("#sort").val('DESC'); else $("#sort").val('ASC');
	$("#myform").submit();
}

//note 用于生成静态页面后跳转
$(function(){
	$("#gotourl").val( document.location.href );	
})

//note 生成静态页
function createPage( obj ){
	
	
	$("#f_action").val('pub');
	$("#tform").submit();
	
}

//note 生成所有静态页
function createPageAll( obj ){

	var ret = window.confirm('全部生成文件需要等待几分钟，确定要生成操作吗?');
	if( !ret ) return;	

	//去除不用的隐藏域，避免执行不了全部生成功能
	$("#tform input[type='hidden']").each(function(){
		if( $(this).attr('id') != 'gotourl' && $(this).attr('id') != 'f_action' &&
			$(this).attr('id') != 't_site_id' ) $(this).remove();
	})
	$("#f_action").val('all');
	$("#tform").submit();
	
}

//note 删除
function delPage(){
	
	var ret = window.confirm('删除有风险，操作需谨慎！');
	if( !ret ) return;
	$("#f_action").val('del');
	$("#tform").submit();
	
}
</script>
<a href="javascript:history.back();" style="color:#F00; margin-right:20px;" >返回上一页</a> 
<a href="doc_<?php echo $TID; ?>.php">新建文档</a>
<a href="docList_<?php echo $TID; ?>.php?type=update_state&Tid=<?php echo $TID; ?>" >修改生成状态为已修改</a>
<form method="GET" id="myform" name="myform">
<table cellpadding="1" cellspacing="1" class="list-div">
	<tr>
		<th colspan="7" align="left" style="padding:0 0 0 10px;"> 搜索</th>   
    </tr>
<?php 
$sql_ = "SELECT TFName, FName 
		FROM Field 
		WHERE TID='$TID' and Depositing='Y'";
$result_ = $db->query($sql_);

while ($row_ = $db->fetch_array($result_, MYSQL_ASSOC)) {
	$Fields_[] = $row_;
}

$count = 5;

if ( count($Fields_) < 5) {
	$count = count($Fields_);
}

echo "<script>var c = $count;</script>";

for ($i = 0; $i < $count; $i++) {?>

	<tr<?php if($i >= max($_GET['searchline'],1)){echo " style=\" display:none\"";} ?> id="TR_<?php echo $i;?>">
		<td width="10%">
		<select name="Field_<?php echo $i ; ?>" onchange="document.getElementById('Field_Name_<?php echo $i ; ?>').value=this.options[this.selectedIndex].text">
<!--	<option></option>-->
		<option value="D_ID" <?php if( $_GET['Field_'.$i] == 'D_ID' ) {echo 'selected="selected"'; $select = true;}else{$select = false;};?>>编号</option>
		<?php
		foreach($Fields_ as $Field_){
			$s = $_GET['Field_'.$i] == $Field_['TFName'] ? 'selected="selected"' : '';
			if( $select == false && $s == '' && strpos( $Field_['FName'], '名称' ) !== false ){//默认选中包含名称的选项
				$s = 'selected="selected"';
			}
			echo "<option value=\"".$Field_['TFName']."\" $s>".$Field_['FName']."</option>";
		}
		?>
<!--	<option value="CreateTime">创建日期</option>
		<option value="Creator">创建者</option>-->
		<option value="MendTime" <?php echo $_GET['Field_'.$i] == 'MendTime' ? 'selected="selected"' : '';?>>修改日期</option>
		<option value="Mender" <?php echo $_GET['Field_'.$i] == 'Mender' ? 'selected="selected"' : '';?>>修改人</option>
        <option value="url" <?php echo $_GET['Field_'.$i] == 'url' ? 'selected="selected"' : '';?>>文档路径</option>
		</select>
		</td>
		<td width="90">
		<select name="Option_<?php echo $i ; ?>">
		<option value="=" <?php echo $_GET['Option_'.$i] == '=' ? 'selected="selected"' : '';?>>等于</option>
		<option value="!=" <?php echo $_GET['Option_'.$i] == '!=' ? 'selected="selected"' : '';?>>不等于</option>
		<option value=">" <?php echo $_GET['Option_'.$i] == '>' ? 'selected="selected"' : '';?>>大于</option>
		<option value="<" <?php echo $_GET['Option_'.$i] == '<' ? 'selected="selected"' : '';?>>小于</option>
		<option value=">=" <?php echo $_GET['Option_'.$i] == '>=' ? 'selected="selected"' : '';?>>大于等于</option>
		<option value="<=" <?php echo $_GET['Option_'.$i] == '<=' ? 'selected="selected"' : '';?>>小于等于</option>
		<option value="like" <?php echo ($_GET['Option_'.$i] == 'like' || $_GET['Option_'.$i] == '')? 'selected="selected"' : '';?>>包含</option>
		<option value="not like" <?php echo $_GET['Option_'.$i] == 'not like' ? 'selected="selected"' : '';?>>不包含</option>
		</select>
		<input type="hidden" name="Field_Name_<?php echo $i ; ?>" id="Field_Name_<?php echo $i ; ?>" />
		</td>
		<td width="440"><input type="text" size="60" name="F_<?php echo $i ; ?>_V" value="<?php echo $_GET['F_'.$i.'_V'];?>"/></td>
        <td width="100"><select name="create_html[]"><option value="">所有生成状态</option>
        <option value="1" <?php if($c_html==1){?>selected="selected"<?php }?>>已生成html</option>
        <option value="2" <?php if($c_html==2){?>selected="selected"<?php }?>>未生成html</option></select></td>
        <td><input type="submit" value="搜索" /></td>
        <td>&nbsp;</td>
		<td width="50"><?php if($i<($count-1)){ ?>
		<select name="Next_<?php echo $i ; ?>" onchange="if(this.options[this.selectedIndex].value==''){hide(<?php echo $i+1; ?>,c)}else{show(<?php echo $i+1;?>)}">
		<option value="" <?php echo $_GET['Next_'.$i] == '' ? 'selected="selected"' : '';?>></option>
		<option value="and" <?php echo $_GET['Next_'.$i] == 'and' ? 'selected="selected"' : '';?>>同时</option>
		<!--option value="or">或者</option-->
		</select><?php }else{echo '<input type="hidden" name="Next_'. $i .'" value="" />';} ?></td>
	</tr>	
<?php }?>
    <input type="hidden" name="sortby" id="sortby" value="<?php echo $sortby;?>" />
     <input type="hidden" name="site_id"  id="t_site_id" value="<?php echo $site_id;?>" />
    <input type="hidden" name="sort" id="sort" value="<?php echo $sort;?>"/>
    <input type="hidden" name="searchline" id="searchline" value="<?php echo max($_GET['searchline'],1);?>"/>
</table>
</form>


<form method="post" onsubmit="return checkFrom();" id="tform" name="tform">
<input type="hidden" name="page" value="<?php echo $page; ?>" />

<input type="hidden" value="true" name="doPost">
<input type="hidden" value="<?php echo $TID;?>" name="TID">	
<input type="hidden" name="site_id"  value="<?php echo $site_id;?>" />	 
<table width="90%" cellpadding="1" cellspacing="1" class="list-div">
	<tr>
		<th colspan="<?php echo count($idStr)+8; ?>" align="left" style="padding:0 0 0 10px;"> 文档列表</th>   
    </tr>
	<tr>
		<td width="6%"><a href="javascript:_sort('D_ID');" style="text-decoration:underline;">ID</a>
		<?php if($sortby == 'D_ID'){ ?><img src="../images/<?php if($sort == 'DESC') echo 'down'; else echo 'up';?>.gif" />
		<?php }?></td><td width="7%">操作</td><td>文档路径</td><?php if($open_fage == 1){ ?>
		<td width="70">是否禁用</td><?php }?><td width="70">生成状态</td><td width="80">
		<a href="javascript:_sort('MendTime');" style="text-decoration:underline;">修改日期</a>
		<?php if($sortby == 'MendTime'){ ?><img src="../images/<?php if($sort == 'DESC') echo 'down'; else echo 'up';?>.gif" />
		<?php }?></td><td width="6%">修改人</td><?php echo $titleStr;?><!--<td>预览路径</td>-->
	</tr>
	<?php

	$result = $db->query($sql);
	while($row = $db->fetch_array($result))
	{
	?>
	<tr>
<?php
$state = 0;
$modify = '';


$tips='';
$file = DOC_ROOT.$row[url];
$isfile = file_exists($file);

if($isfile){
  $tips = '<font color="green">已生成html</font>';
  
  $cr_time = $row['CreateTime'];
  
  $modify = ($row[MendTime] > $cr_time) ? '<font color="red">已修改</font>' : '';
  
} else {
	$tips = '<font color="red">未生成html</font>';
}
$q = $_SERVER['QUERY_STRING'];
$suffix_url = "D_ID={$row['D_ID']}";
if(!empty($q))
{
	if(substr_count($q,'D_ID=') > 0)
	{
	    $arr = explode('&',$q);
		$suffix_url = str_replace($arr[0],$suffix_url,$q); 
		
	}else
	{ 
		$suffix_url = $suffix_url.'&'.$q;
	}
}

if ( substr_count($suffix_url, 'site_id=') == 0 ) {
	$suffix_url = $suffix_url.'&site_id='.$site_id;
}
	

echo "<td><input type=\"checkbox\" value=\"{$row[D_ID]}\" name=\"ID[]\">{$row[D_ID]}</td>";
echo "<td>";
echo ($Template->PID==0)?"[<a href=\"preview.php?do=view&TID={$Template->TID}&D_ID={$row[D_ID]}\" target=\"_blank\">预览</a>]":"[<a href=\"preview.php?do=view&TID={$Template->PID}&D_ID={$prow[D_ID]}\" target=\"_blank\">预览</a>]";
echo "<a href=\"doc_$TID.php?{$suffix_url}\" target=\"_self\">[编辑]</a></td>";
echo "<td><a href=\"".(preg_match("/^https?:/i",$row['url'])?'':DOC_URL)."{$row[url]}\" target=\"_blank\">{$row[url]}</a></td>";
//echo "<td><a href=\"".getUrl($row[url])."\" target=\"_blank\">{$row[url]}</a></td>";
if($open_fage == 1){
  if($row['is_open'] == 0 )
  {
    if($is_single == 0 )//是否单页管理
       echo '<td><font color="#00CC00">已启用</font></td>';  
	else
	   echo '<td><font color="#00CC00">已启用</font>  &nbsp;&nbsp;<a href="?action=single&tem_id='.$row['D_ID'].'&is_open=1">点击禁止</a> </td>';  
  }else
  {
      if($is_single == 0 )//是否单页管理
       echo '<td><font color="red">已禁止</font></td>';  
	 else
	   echo '<td><font color="red">已禁止</font>  &nbsp;&nbsp;<a href="?action=single&tem_id='.$row['D_ID'].'&is_open=0">点击启动</a> </td>';  
  }
}
echo "<td>".$tips.' '.$modify."</td>";
echo "<td>".date("Y-m-d H:i:s",$row[MendTime])."</td>";
echo "<td>".getAdminName($row[MenderID])."</td>";
for($i=0;$i<count($idStr);$i++)
{
if( !in_array( $fieldStr[$i], array('url','MenderID','MendTime')) ) echo "<td>".$row[$fieldStr[$i]]."</td>";
}
//echo ($Template->PID==0)?"<td><a href=\"".(eregi("^https?:",$row['url'])?'':DOC_URL)."{$version_url}{$row[url]}\" target=\"_blank\">{$version_url}{$row[url]}</a></td>":"<td><a href=\"".(eregi("^https?:",$prow['url'])?'':DOC_URL)."{$version_url}{$prow[url]}\" target=\"_blank\">{$version_url}{$prow[url]}</a></td>";
		?>
	</tr>
	<?php
	}
	?>
	<tr>
	    <td><input type="checkbox" name="checkall" value="checked" onclick="v=document.getElementsByName('ID[]');if(this.checked){for(i=0;i<v.length;i++)v[i].checked=true;}else{for(i=0;i<v.length;i++)v[i].checked=false;}">全选</td>

		<td colspan="<?php echo count($idStr)+5; ?>">
        <input type="hidden" id="f_action" name="action" value="" />
        <input type="hidden" id="gotourl" name="gotourl" />
		<input type="button" value="删除" onclick="delPage()">
		<input type="button" value="生成静态页" onclick="createPage(this)">
        <!--<input type="radio" name="action" value="pubtmp">发布预览&nbsp;&nbsp;-->
        <input type="button" value="全部生成静态页" onclick="createPageAll(this)" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        <?php
		/*修改分页功能，显示*/
		$i = $page - 5;
		if ($i < 1) {
			$i = 1;
		}
		$j = $i + 9;		
		if ($j > $page_num) {
			$j = $page_num;
		}
		$str = '';
		$str .= ($page == 1) ? '' : '<a href="?'.get_page_no('page',($page-1)).'">上一页</a>&nbsp;';
		for ($i; $i <= $j; $i++) {		    
		    $str .= ($page == $i) ? '<span style="color:#FF0000;font-weight:bold">'.$i.'</span>&nbsp;' : '<a href="?'.get_page_no('page',$i).'">'.$i.'</a>&nbsp;';		    
		}
		$str .= ($page == $j) ? '' : '<a href="?'.get_page_no('page',($page+1)).'">下一页</a>&nbsp';
		$str .= '&nbsp第 '.$page.' / '.$page_num.' 页';
		$str .= '&nbsp&nbsp&nbsp<input id="gotopage" type="text" size="4" onkeypress="if(event.keyCode==13){window.location.href=\'?'.get_page_no('page',($page)).'&page=\'+this.value}" />';
		$str .= '<input type="button" value=" GO " onclick="var a = document.getElementById(\'gotopage\').value;if( !a ){alert(\'请输入页码！\');return;}window.location.href=\'?'.get_page_no('page',($page)).'&page=\'+a;"/>';
		$str .= '共有'.$total.'条记录';
		echo $str;
		?>
        </td>
	</tr>
</table>
</form>
<?php
include("../inc/foot.php");

function  updateNoFileExistsTime($tables) {
	
	$prefix_url = DOC_ROOT;
	
	$sql = "SELECT D_ID, url FROM {$tables} ";
	$result = $GLOBALS['db']->query($sql);
	
	$update_id = '';
	while ($row = $GLOBALS['db']->fetch_array($result)) {
		
		if (!file_exists($prefix_url.$row['url'])) {
			$update_id .= empty($update_id) ? $row['D_ID'] : ','.$row['D_ID'];
		}
		
	}
	
	if (!empty($update_id)) {
		$sql = "UPDATE {$tables} SET CreateTime = 0 WHERE FIND_IN_SET(D_ID, '{$update_id}') ";
		$GLOBALS['db']->query($sql);
	}
}

function getAdminIdByName($name)
{

	$sql = "select AID from Admin where AName='$name'";

	$result = $GLOBALS['db']->query($sql);
	if($row = $GLOBALS['db']->fetch_array($result))
	{
		$name = $row['AID'];

	}
	return $name;
}
/**
* @getAdminName//取得用户名
*/
function getAdminName($MenderID)
{
    $sql = "select `AName` from Admin where `AID`='$MenderID'";
	$result = $GLOBALS['db']->query($sql);
	if($row = $GLOBALS['db']->fetch_array($result))
	{
		$name = $row['AName'];
		//$name = $row['AName'];
	}
	return $name;  
}
/**
* @getModifyState//取得文章修改状态
*/
function getModifyState($fromid,$table)
{
    switch($table)
	{
	   case 'Table_13':
	     $sql = "select `modify_status` from `topic_article` where `ar_id`='$fromid'";
	     break;
	   case 'Table_15':
	     $sql = "select `modify_status` from `category` where `cat_id`='$fromid'";
	     break;
	   case 'Table_19':
	     $sql = "select `modify_status` from `tag` where `tag_id`='$fromid'";
	     break;
	}
	if($sql)
	{
		$result = $GLOBALS['db']->query($sql);
		if($row = $GLOBALS['db']->fetch_array($result))
		{
			$status = $row[0];
		}
	}
	return $status ? $status : 0;     
}
/**
* @ delPageList//删除含有分页的列表页面
* @ 参数$ID//id,$whereid//条件ID,$DTName//表名
* @ return boolean
*/
function delPageList($ID,$whereid,$DTName)
{
   
   $url = $GLOBALS['db']->getOne("select `url` from $DTName where $whereid = $ID");
   $dirurl = dirname($url);
   if($dirurl)
   {
     if($dirurl != '/wondershare.com') dir_clear(DOC_ROOT.$dirurl);
   }else{
     return false;
   }
}
/*
* 删除指定目录下的所有文件
* @param String $dir 要进行操作的路径
*/
function dir_clear($dir)
{   
	$directory = dir($dir); //创建一个dir类(PHP手册上这么说的)，用来读取目录中的每一个文件
	while($entry = $directory->read())
	{	
		//循环每一个文件,并取得文件名$entry
		$filename = $dir.'/'.$entry; //取得完整的文件名，带路径的
		if(is_file($filename)) 
		{ 
			//如果是文件，则执行删除操作
			$path_parts = pathinfo($filename);
			if(preg_match("/^[0-9a-zA-Z]{1,}\.html/i",$path_parts['basename'])) unlink($filename);
		}
	}
	$directory->close(); //关闭读取目录文件的类
}

?>
